<template>
  <div class="department-container">
    <el-card class="search-card">
      <div class="search-bar">
        <span class="search-title">社区搜索</span>
        <el-input
          v-model="searchKeyword"
          placeholder="请输入关键词"
          class="search-input"
          clearable
        />
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button
          type="primary"
          plain
          class="add-btn"
          @click="handleOptions('add')"
          >新增</el-button
        >
      </div>
    </el-card>
    <el-card class="list-card">
      <div class="list-title">社区列表</div>
      <div v-for="item in departments" :key="item.id" class="department-item">
        <div class="item-left">
          <div class="item-header">
            <span class="item-title">{{ item.departmentName }}</span>
          </div>
          <div class="item-content">
            <div><strong>主要负责人：</strong>{{ item.username }}</div>
            <div><strong>工作职责：</strong>{{ item.responsibilities }}</div>
          </div>
        </div>
        <div>
          <el-button plain @click="handleOptions('edit', item)">编辑</el-button>
          <el-button type="danger" plain @click="handleOptions('del', item)"
            >删除</el-button
          >
        </div>
      </div>
    </el-card>
    <div class="pagination-container">
      <span class="total-count">总共 {{ total }} 个项目</span>
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="prev, pager, next, jumper, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑模态框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增社区' : '编辑社区'"
      width="800px"
      class="department-dialog"
      @close="resetDialog"
    >
      <el-form
        :model="dialogForm"
        label-width="120px"
        class="dialog-form"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="标题" prop="departmentName">
          <el-input
            v-model="dialogForm.departmentName"
            placeholder="请输入社区名称"
          />
        </el-form-item>
        <el-form-item label="主要负责人" prop="headUserId">
          <el-select
            v-model="dialogForm.headUserId"
            placeholder="请选择负责人"
            @change="changePerson"
            filterable
          >
            <el-option
              v-for="person in leaderOptions"
              :key="person.value"
              :label="person.label"
              :value="person.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主要职责" prop="responsibilities">
          <el-input
            v-model="dialogForm.responsibilities"
            type="textarea"
            :rows="4"
            placeholder="请输入主要职责"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave(ruleFormRef)"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import {
  getList,
  addData,
  updateData,
  getInfo,
  deleteData,
} from "@/api/department";
import { listUser, getUser } from "@/api/system/user.js";
import { ElMessage, ElMessageBox } from "element-plus";

const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const departments = ref([]);

const dialogVisible = ref(false);
const dialogType = ref("add"); // add | edit
const dialogForm = ref({
  departmentName: "",
  headUserId: "",
  responsibilities: "",
  username: "",
});
const leaderOptions = ref([]);
const userTotal = ref(0);
const userPageNum = ref(1);
const userPageSize = ref(10);
const ruleFormRef = ref(null);

const rules = reactive({
  departmentName: [{ required: true, message: "请输入", trigger: "blur" }],
  headUserId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  responsibilities: [{ required: true, message: "请输入", trigger: "blur" }],
});

onMounted(() => {
  getUserList();
  fetchTableData();
});
const getUserList = async () => {
  const { rows, total } = await listUser({
    pageSize: userPageSize.value,
    pageNum: userPageNum.value,
  });
  leaderOptions.value = rows.map((item) => {
    return {
      value: item.userId,
      label: item.userName,
    };
  });
  userTotal.value = total || 0;
};
const fetchTableData = async () => {
  let params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    departmentName: searchKeyword.value,
    type: "社区",
  };
  const res = await getList(params);
  departments.value = res?.rows || [];
  total.value = res?.total || 0;
};
const handleOptions = async (type, item) => {
  if (type === "del") {
    ElMessageBox.confirm("确认删除该社区吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        try {
          await deleteData(item.id);
          ElMessage.success("删除成功");
          fetchTableData();
        } catch (error) {
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
    return;
  }
  dialogType.value = type;
  dialogVisible.value = true;
  if (type === "edit" && item) {
    let res = await getInfo(item.id);
    dialogForm.value = {
      ...res.data,
      headUserId: Number(res.data.headUserId),
    } || { ...item, headUserId: Number(item.headUserId) };
  } else if (type === "add") {
    dialogForm.value = {
      departmentName: "",
      headUserId: "",
      responsibilities: "",
      username: "",
    };
  }
};
function onSearch() {
  currentPage.value = 1;
  fetchTableData();
}
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1;
  fetchTableData();
}
function handleCurrentChange(val) {
  currentPage.value = val;
  fetchTableData();
}
function resetDialog() {
  dialogForm.value = {
    departmentName: "",
    headUserId: "",
    responsibilities: "",
    username: "",
  };
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
}
const changePerson = async (val) => {
  if (val) {
    const { code, data } = await getUser(val);
    if (code === 200) {
      dialogForm.value.username = data?.user?.userName;
    } else {
      dialogForm.value.username = "";
      ElMessage.error("获取用户失败");
    }
  }
};
const handleSave = async (formEl) => {
  if (!formEl) return;
  try {
    await formEl.validate();
    // 验证通过，这里可以添加保存逻辑
    console.log("表单验证通过，准备保存数据", dialogForm.value);
    // return
    if (dialogType.value === "add") {
      await addData({
        ...dialogForm.value,
        headUserId: dialogForm.value.headUserId.toString(),
        type: "1",
      });
      currentPage.value = 1;
      ElMessage.success("添加成功");
    } else {
      await updateData({
        ...dialogForm.value,
        headUserId: dialogForm.value.headUserId.toString(),
      });
      ElMessage.success("修改成功");
    }
    dialogVisible.value = false;
    resetDialog();
    fetchTableData();
  } catch (error) {
    console.log("表单验证失败", error);
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
